
<template>
  <div>
    <el-dialog
        :title="title"
        :model-value="visible"
        :before-close="handleClose"
        class="load-scene-dialog"
    >
      <div class="load-scene-dialog-container">
        <div class="scene-list">
          <ul>
            <li v-for="item in resourceLibrarySceneList" class="scene-item">
              <el-checkbox :label="item.id" v-model="selectedScenes"  @change="checkScene(item, $event)"/>
              <span class="scene-name" :title="item.name" @click="switchScene(item, 'normal')">{{ item.name }}</span>
            </li>
          </ul>
        </div>

        <el-form
            class="user-edit-form m-auto mt-1"
            ref="ruleFormRef"
            :model="ruleForm"
            status-icon
        >
          <div>
            <el-form-item label="选择场景"
                          prop="sceneType"
                          :rules="{
                          required: true,
                          message: '请选择场景',
                          trigger: ['change'],
          }" >
              <el-select v-model="detailData" disabled clearable>
                <el-option v-for="item in resourceLibrarySceneList"
                           :key="item.id"
                           :label="item.name"
                           :value="item.id"
                           :title="item.name"
                           :style="{ width: item.name.length > 18 ? '360px' : 'auto' }"
                >

                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="选择集群" />
            <el-form-item
                label="集群"
                prop="clusterID"
                :rules="{
            required: true,
            message: '请选择集群',
            trigger: ['change'],
          }"
            >
              <el-select filterable v-model="ruleForm.clusterID" placeholder="请选择" clearable>
                <el-option
                    v-for="cluster in clusterList"
                    :key="cluster?.ID"
                    :label="cluster?.name"
                    :value="cluster?.ID"
                />
              </el-select>
            </el-form-item>

          </div>

          <div>
            <el-form-item label="选择计算节点" />
            <el-form-item
                v-for="computedNodeKey in formProps.computerNames"
                :key="computedNodeKey"
                :label="computedNodeKey"
                :prop="['computer', computedNodeKey]"
                :rules="{
            required: true,
            message: '请选择计算节点',
            trigger: ['change'],
          }"
            >
              <el-select
                  v-model="ruleForm['computer'][computedNodeKey]"
                  placeholder="请选择计算节点"
                  filterable
                  clearable
              >
                <el-option
                    v-for="computedNode in computedNodeList"
                    :key="computedNode?.ID"
                    :label="computedNode?.name"
                    :value="computedNode?.ID"
                />
              </el-select>
            </el-form-item>
          </div>

          <div>
            <el-form-item label="选择集群网络" />
            <el-form-item
                v-for="networkNodeKey in formProps.networkNames"
                :key="networkNodeKey"
                :label="networkNodeKey"
                :prop="['network', networkNodeKey]"
                :rules="{
            required: true,
            message: '选择集群网络',
            trigger: ['change'],
          }"
            >
              <el-select
                  v-model="ruleForm['network'][networkNodeKey]"
                  placeholder="请选择集群网络"
                  filterable
                  clearable
              >
                <el-option
                    v-for="networkNode in networkNodeList"
                    :key="networkNode?.ID"
                    :label="networkNode?.name"
                    :value="networkNode?.ID"
                />
              </el-select>
            </el-form-item>
          </div>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSave">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref, watch } from 'vue';
import {
  getCluster,
  getScenesList,
  importScenes,
  getSceneType
} from '@/api/topo/topo';
import {ElMessage} from 'element-plus';
import {omit} from 'lodash';

const resourceLibrarySceneList = ref([])
const detailData = ref(null);
const typeList = ref(null);
const props = defineProps({
  title: {
    type: String,
    default: '',
  },
  visible: {
    type: Boolean,
    default: false,
  },
});

const emits = defineEmits(['close', 'success']);

const ruleFormRef = ref();
const ruleForm = ref({
  clusterID: '',
  computer: {},
  network: {},
  sceneType: ''
});
const scenesId = ref('');
const formProps = reactive({
  computerNames: [],
  networkNames: [],
});
const clusterList = ref([]);

const computedNodeList = ref([]);
const networkNodeList = ref([]);

const onGetScenesList = async () => {
  const params = {
    page: 1,
    pageSize: 9999,
  };
  try {
    const res = await getScenesList(params);
    resourceLibrarySceneList.value = res.data?.list
  } catch (error) {}
};

const getSceneTypeFunc = async () => {
  let res = await getSceneType();
  if (!(res instanceof Error)) {
    typeList.value = res.data;
  }
};

const selectedScenes = ref([]);
const collectionScene = ref([]);
/**
 * 勾选场景时触发
 */
const checkScene = (item, event) => {

  // 如果当前场景未被选中（即 event === true），需要进行校验
  if (event && selectedScenes.value.length > 1) {
    ruleFormRef.value.validate(async valid => {
      if (!valid) {
        // 校验不通过，显示警告消息并移除新增的 ID
        ElMessage.warning('请完善上一个场景内容或取消上一个勾选！');
        selectedScenes.value = selectedScenes.value.filter(id => id !== item.id);
        return;
      } else {

        collectionSceneIsEmpty(selectedScenes.value[selectedScenes.value.length - 2]);

        // 清空表单
        ruleFormRef.value?.resetFields()
        formProps.networkNames = null
        formProps.computerNames = null
        ruleForm.value.clusterID = ''
        detailData.value = null;
      }

      // 校验通过后，允许切换场景
      toggleScene(item, event);
    });
  } else {
    collectionScene.value = collectionScene.value.filter(cItem => cItem.sceneID !== item.id);

    // 清空表单
    ruleFormRef.value?.resetFields()
    formProps.networkNames = null
    formProps.computerNames = null
    ruleForm.value.clusterID = ''
    detailData.value = null;

    // 当前场景被取消勾选，直接处理
    toggleScene(item, event);

    if (!event) {

      detailData.value = selectedScenes.value[0];
      // 取消直接切换到最后一个
      switchScene({ id: selectedScenes.value[0] }, 'del');
    }
  }
};

/**
 * 根据id判断是否存在
 * @param id
 */
const collectionSceneIsEmpty = (id) =>{
  let temp = {
    clusterID: ruleForm.value.clusterID,
    computer: Object.assign({}, ruleForm.value.computer),
    network: Object.assign({}, ruleForm.value.network),
    sceneType: ruleForm.value.sceneType
  };

  // 判断是否存在、存在更新
  let flag = false;
  collectionScene.value.forEach(item =>{
    if (item.sceneID === id) {
      flag = true;

      item.data = temp;
    }
  })

  if (!flag) {
    // 收集上一个
    collectionScene.value.push({
      sceneID: id,
      data: temp
    });
  }
}

/**
 * 切换
 * @param scene
 */
const switchScene = (scene, type) => {

  // 没勾选上切换
  if (!selectedScenes.value.includes(scene.id)) {
    return;
  }

  if (type === 'normal') {
    // 切换之前
    collectionSceneIsEmpty(detailData.value);
  }

  // 判断收集里面是否存在
  let flag = false;
  collectionScene.value.forEach(item =>{
    if (item.sceneID === scene.id) {
      ruleForm.value = {
        clusterID: item.data.clusterID,
        computer: Object.assign({}, item.data.computer),
        network: Object.assign({}, item.data.network),
        sceneType: item.data.sceneType
      };
      detailData.value = scene.id;

      // 遍历数据
      let tempObj = {};
      resourceLibrarySceneList.value.forEach(item=>{
        if(item.id === scene.id){
          tempObj = item;
          ruleForm.value.sceneType = item.sceneType
        }
      })

      formProps.computerNames = [].concat(
          tempObj?.computerNames || [],
      );

      formProps.networkNames = [].concat(tempObj?.networkNames || []);
    } else {
      flag = true;
    }
  })
}

/**
 * 切换场景的逻辑
 */
const toggleScene = (item, event) => {
  if (event) {
    // 勾选当前场景
    choiceScene(item.id);
    detailData.value = item.id;
  } else {
    // 取消勾选当前场景
    selectedScenes.value = selectedScenes.value.filter(id => id !== item.id); // 移除当前场景
  }
};

const choiceScene = async (sceneID)=>{
  ruleForm.value.computer = {}
  ruleForm.value.network = {}
  const _data = Object.assign(ruleForm.value, {});

  scenesId.value = sceneID || '';
  let tempObj = {};
  resourceLibrarySceneList.value.forEach(scene=>{
    if(scene.id === sceneID){
      detailData.value = scene.id;
      tempObj = scene;
      ruleForm.value.sceneType=scene.sceneType
    }
  })

  Object.entries(omit(tempObj, 'id')).map(([label, keys = []]) => {
    if (label==='computerNames'||label==='networkNames'){
      if (keys!==null){
        const _label = label === 'computerNames' ? 'computer' : 'network';
        keys?.forEach(key => {
          _data[_label][key] = '';
        });
      }
    }
  });

  formProps.computerNames = [].concat(
      tempObj?.computerNames || [],
  );
  formProps.networkNames = [].concat(tempObj?.networkNames || []);
  ruleForm.value = _data;
}

watch(
  () => props.visible,
  async val => {
    if (val) {
      ruleFormRef.value?.resetFields()
      formProps.networkNames = null
      formProps.computerNames = null
      ruleForm.value.clusterID = ''
      detailData.value = null;
      await getSceneTypeFunc();
      await onGetScenesList();
      await onGetCluster();
    } else {
      selectedScenes.value = [];
      collectionScene.value = [];
    }
  },
);

watch(
  () => ruleForm.value.clusterID,
  val => {
    const _target = clusterList.value.find(item => item?.ID === val);
    computedNodeList.value = [].concat(_target?.computers || []);
    networkNodeList.value = [].concat(_target?.networks || []);
  },
);

const onGetCluster = async () => {
  try {
    const res = await getCluster({
      page: 1,
      pageSize: 999,
      keyword: '',
    });
    const _list = [].concat(res.data?.list || []);

    // ruleForm.value.clusterID = _list[0]?.ID;
    clusterList.value = _list;
  } catch (error) {}
};

const handleClose = () => {
  ruleFormRef.value?.resetFields();
  emits('close', false);
};

const handleSave = async () => {
  ruleFormRef.value.validate(async valid => {
    if (valid) {
      const params = {
        sceneID: scenesId.value,
        data: Object.assign({}, ruleForm.value),
      };

      collectionSceneIsEmpty(params.sceneID);

      try {

        const collectionPromises = collectionScene.value.map(item => importScenes(item));

        // 等待所有操作完成
        await Promise.all(collectionPromises);
        handleClose();
        emits('success');
      } catch (error) {
        ElMessage.error({ message: error?.msg || '导入失败' });
      }
    }
  });
};
</script>
<style lang="scss" scoped>
:deep(.load-scene-dialog) {
  width: 860px;
  .el-form {
    width: 460px;
    height: 380px;
    overflow-y: auto;
    margin: 20px 0;

    .el-form-item__label {
      width: 120px;
    }
  }

  .load-scene-dialog-container {
    display: flex;

    .scene-list {
      width: 380px;
      height: 400px;
      overflow-y: auto;
      margin-right: 20px;
      border: 1px solid #e0e0e0;
      border-radius: 4px;
      padding: 10px;
      .scene-item {
        display: flex;
        align-items: center;
        margin-bottom: 20px;

        .el-checkbox {
          margin-right: 12px;
        }

        .el-checkbox__label {
          display: none;
        }

        .scene-name {
          flex: 1;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          cursor: pointer;
        }
      }
    }
  }
}
</style>
